<template>
  <div v-if="isDialog" style="align-items: center; width: 100%; height: 50px">
    <span
      style="
        font-size: 25px;
        align-content: center;
        font-weight: 600;
        display: flex;
        justify-content: center;
      "
    >
      账号注册
    </span>
  </div>
  <div v-else class="login-title">
    <div class="title-content">
      <img class="logo" src="@/assets/image/logo.png" alt="logo" />
      <h2 class="title-text">
        {{ WEBSITE_NAME }}
      </h2>
    </div>
  </div>

  <!-- 注册表单 -->
  <div class="login-form-container">
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="registerRules"
      class="login-form"
      @submit.prevent="handleRegister"
    >
      <!-- 邮箱输入框 -->
      <el-form-item prop="email" class="form-item">
        <div class="input-label">
          <span class="label-text">邮箱地址</span>
        </div>
        <el-input
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          size="large"
          class="login-input"
        >
          <template #prefix>
            <svg-icon icon-class="email" class="input-icon" />
          </template>
          <template #append>
            <el-select v-model="emailSuffix" class="email-select" placeholder="邮箱后缀">
              <el-option label="@qq.com" value="@qq.com" />
              <el-option label="@163.com" value="@163.com" />
            </el-select>
          </template>
        </el-input>
      </el-form-item>

      <!-- 验证码输入框 -->
      <el-form-item prop="verifyCode" class="form-item">
        <div class="input-label">
          <span class="label-text">验证码</span>
        </div>
        <el-input
          v-model="registerForm.verifyCode"
          placeholder="请输入验证码"
          size="large"
          class="login-input"
        >
          <template #prefix>
            <svg-icon icon-class="captcha" class="input-icon" />
          </template>
          <template #suffix>
            <el-button
              :disabled="isCountingDown"
              link
              type="primary"
              class="verify-btn"
              @click="sendVerifyCode"
            >
              {{ countDownText }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <!-- 密码输入框 -->
      <el-form-item prop="password" class="form-item">
        <div class="input-label">
          <span class="label-text">密码</span>
        </div>
        <el-input
          v-model="registerForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          size="large"
          class="login-input"
          @input="checkPasswordStrength"
        >
          <template #prefix>
            <el-tooltip
              effect="dark"
              placement="right"
              :content="`密码要求：
              · 长度至少8位
              · 包含大小写字母
              · 包含数字
              · 包含特殊字符`"
            >
              <svg-icon icon-class="password" class="input-icon" />
            </el-tooltip>
          </template>
          <template #suffix>
            <div class="password-toggle" @click="showPassword">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                class="toggle-icon"
              />
            </div>
          </template>
        </el-input>

        <!-- 密码强度指示器 -->
        <div v-if="registerForm.password" class="password-strength">
          <div class="strength-label">密码强度：</div>
          <div class="strength-bars">
            <div
              class="strength-bar"
              :class="{
                weak: passwordStrength >= 1,
                medium: passwordStrength >= 2,
                strong: passwordStrength >= 3
              }"
            />
            <div
              class="strength-bar"
              :class="{
                medium: passwordStrength >= 2,
                strong: passwordStrength >= 3
              }"
            />
            <div
              class="strength-bar"
              :class="{
                strong: passwordStrength >= 3
              }"
            />
          </div>
          <div class="strength-text">
            {{ passwordStrengthText }}
          </div>
        </div>
      </el-form-item>

      <!-- 确认密码输入框 -->
      <el-form-item prop="confirmPassword" class="form-item">
        <div class="input-label">
          <span class="label-text">确认密码</span>
        </div>
        <el-input
          v-model="registerForm.confirmPassword"
          :type="confirmPasswordType"
          placeholder="请再次输入密码"
          size="large"
          class="login-input"
        >
          <template #prefix>
            <svg-icon icon-class="password" class="input-icon" />
          </template>
          <template #suffix>
            <div class="password-toggle" @click="showConfirmPassword">
              <svg-icon
                :icon-class="confirmPasswordType === 'password' ? 'eye' : 'eye-open'"
                class="toggle-icon"
              />
            </div>
          </template>
        </el-input>
      </el-form-item>

      <!-- 协议同意 -->
      <div class="form-options">
        <el-checkbox v-model="registerForm.agreeToTerms" class="terms-checkbox">
          <span class="checkbox-text">
            我已阅读并同意
            <el-button link type="primary" class="terms-link" @click="showTerms">
              《用户协议》
            </el-button>
            和
            <el-button link type="primary" class="terms-link" @click="showPrivacy">
              《隐私政策》
            </el-button>
          </span>
        </el-checkbox>
      </div>

      <!-- 注册按钮 -->
      <el-form-item class="login-button-item">
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="login-button"
          @click="handleRegister"
        >
          <span v-if="!loading" class="button-text">注册</span>
          <span v-else class="button-text">注册中...</span>
        </el-button>
      </el-form-item>

      <!-- 登录链接 -->
      <div class="register-link">
        <span class="register-text">已有账号？</span>
        <el-button link type="primary" class="register-btn" @click="$emit('switch-mode')">
          立即登录
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElNotification } from 'element-plus';
import SvgIcon from '@/components/common/SvgIcon/index.vue';
// import { registerApi, sendEmailCodeApi } from '@/api/auth';
import { WEBSITE_NAME } from '@/constants';

const registerFormRef = ref<FormInstance>();
const loading = ref<boolean>(false);
const passwordType = ref<string>('password');
const confirmPasswordType = ref<string>('password');
const emailSuffix = ref<string>('@qq.com');
const isCountingDown = ref<boolean>(false);
const countDown = ref<number>(0);
const passwordStrength = ref<number>(0);

defineProps({
  isDialog: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['switch-mode', 'register-success']);

// 表单数据
const registerForm = reactive({
  email: '',
  verifyCode: '',
  password: '',
  confirmPassword: '',
  agreeToTerms: false
});

// 表单验证规则
const registerRules = reactive({
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '邮箱长度在 2 到 20 个字符',
      trigger: 'blur'
    }
  ],
  verifyCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      len: 6,
      message: '验证码长度为6位',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 8,
      max: 20,
      message: '密码长度在 8 到 20 个字符',
      trigger: 'blur'
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && !isStrongPassword(value)) {
          callback(new Error('密码强度不够，请包含大小写字母、数字和特殊字符'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 计算属性
const countDownText = computed(() =>
  isCountingDown.value ? `${countDown.value}秒后重发` : '发送验证码'
);

const passwordStrengthText = computed(() => {
  const strengthMap = {
    0: '弱',
    1: '弱',
    2: '中',
    3: '强'
  };
  return strengthMap[passwordStrength.value as keyof typeof strengthMap] || '弱';
});

// 密码强度检查
const checkPasswordStrength = (value: string) => {
  let strength = 0;
  if (value.length >= 8) strength++;
  if (/[a-z]/.test(value)) strength++;
  if (/[A-Z]/.test(value)) strength++;
  if (/\d/.test(value)) strength++;
  if (/[!@#$%^&*(),.?":{}|<>]/.test(value)) strength++;

  passwordStrength.value = Math.min(Math.floor(strength / 2), 3);
};

// 密码强度验证
const isStrongPassword = (password: string): boolean => {
  const hasLower = /[a-z]/.test(password);
  const hasUpper = /[A-Z]/.test(password);
  const hasNumber = /\d/.test(password);
  const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
  return hasLower && hasUpper && hasNumber && hasSpecial;
};

// 显示密码
const showPassword = () => {
  passwordType.value = passwordType.value === 'password' ? 'text' : 'password';
};

// 显示确认密码
const showConfirmPassword = () => {
  confirmPasswordType.value = confirmPasswordType.value === 'password' ? 'text' : 'password';
};

// 发送验证码
const sendVerifyCode = async () => {
  if (!registerForm.email) {
    ElNotification({
      title: '提示',
      message: '请先输入邮箱',
      type: 'warning'
    });
    return;
  }

  try {
    const fullEmail = registerForm.email + emailSuffix.value;
    // await sendEmailCodeApi({ email: fullEmail });

    ElNotification({
      title: '成功',
      message: '验证码已发送到您的邮箱',
      type: 'success'
    });

    // 开始倒计时
    isCountingDown.value = true;
    countDown.value = 60;
    const timer = setInterval(() => {
      countDown.value--;
      if (countDown.value <= 0) {
        clearInterval(timer);
        isCountingDown.value = false;
      }
    }, 1000);
  } catch (error) {
    console.error('发送验证码失败:', error);
  }
};

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return;

  try {
    const valid = await registerFormRef.value.validate();
    if (!valid) return;

    if (!registerForm.agreeToTerms) {
      ElNotification({
        title: '提示',
        message: '请先同意用户协议和隐私政策',
        type: 'warning'
      });
      return;
    }

    loading.value = true;

    try {
      const fullEmail = registerForm.email + emailSuffix.value;
      const registerData = {
        ...registerForm,
        email: fullEmail
      };

      // await registerApi(registerData);

      ElNotification({
        title: '注册成功',
        message: '欢迎加入我们！',
        type: 'success'
      });

      emit('register-success');
    } catch (error) {
      console.error('注册失败:', error);
    }
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    loading.value = false;
  }
};

// 显示用户协议
const showTerms = () => {
  ElNotification({
    title: '用户协议',
    message: '这里显示用户协议内容',
    type: 'info'
  });
};

// 显示隐私政策
const showPrivacy = () => {
  ElNotification({
    title: '隐私政策',
    message: '这里显示隐私政策内容',
    type: 'info'
  });
};
</script>

<style lang="scss" scoped>
@use '../index.scss';

// 标题样式
.dialog-title {
  text-align: center;
  margin-bottom: 16px;

  .dialog-title-text {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
}

.login-title {
  text-align: center;
  margin-bottom: 20px;

  .title-content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4px;

    .logo {
      width: 40px;
      height: 40px;
      margin-right: 12px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .title-text {
      font-size: 26px;
      font-weight: 700;
      color: #303133;
      margin: 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }
  }

  .title-subtitle {
    font-size: 15px;
    color: #909399;
    font-weight: 400;
  }
}

// 表单容器
.login-form-container {
  .login-form {
    .form-item {
      margin-bottom: 12px;

      .input-label {
        margin-bottom: 4px;

        .label-text {
          font-size: 12px;
          font-weight: 500;
          color: #606266;
        }
      }

      // 输入框样式
      :deep(.login-input) {
        .el-input__wrapper {
          height: 40px;
          border-radius: 8px;
          border: 2px solid #e4e7ed;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

          &:hover {
            border-color: #c0c4cc;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          }

          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);
          }
        }

        .el-input__inner {
          height: 36px;
          font-size: 14px;
          color: #303133;

          &::placeholder {
            color: #c0c4cc;
            font-size: 12px;
          }
        }

        .input-icon {
          font-size: 15px;
          color: #909399;
          margin-right: 8px;
        }
      }
    }

    // 邮箱选择器
    :deep(.email-select) {
      .el-select__wrapper {
        height: 40px;
        border-radius: 0 8px 8px 0;
        border-left: none;

        .el-select__placeholder {
          font-size: 12px;
          color: #c0c4cc;
        }
      }
    }

    // 验证码按钮
    .verify-btn {
      font-size: 12px;
      font-weight: 500;
      padding: 0 8px;

      &:disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }
    }

    // 密码强度指示器
    .password-strength {
      display: flex;
      align-items: center;
      margin-top: 6px;
      gap: 8px;

      .strength-label {
        font-size: 11px;
        color: #909399;
      }

      .strength-bars {
        display: flex;
        gap: 2px;

        .strength-bar {
          width: 20px;
          height: 4px;
          border-radius: 2px;
          background-color: #e4e7ed;
          transition: all 0.3s ease;

          &.weak {
            background-color: #f56c6c;
          }

          &.medium {
            background-color: #e6a23c;
          }

          &.strong {
            background-color: #67c23a;
          }
        }
      }

      .strength-text {
        font-size: 11px;
        font-weight: 500;

        &.weak {
          color: #f56c6c;
        }

        &.medium {
          color: #e6a23c;
        }

        &.strong {
          color: #67c23a;
        }
      }
    }

    // 性别选择
    .gender-group {
      display: flex;
      gap: 16px;

      .gender-radio {
        :deep(.el-radio__label) {
          .radio-text {
            font-size: 12px;
            color: #606266;
          }
        }

        :deep(.el-radio__input.is-checked .el-radio__inner) {
          background-color: #409eff;
          border-color: #409eff;
        }
      }
    }

    // 表单选项
    .form-options {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      margin-bottom: 14px;

      .terms-checkbox {
        :deep(.el-checkbox__label) {
          .checkbox-text {
            font-size: 11px;
            color: #606266;
            font-weight: 400;
            line-height: 1.4;
          }
        }

        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: #409eff;
          border-color: #409eff;
        }

        .terms-link {
          font-size: 11px;
          padding: 0;
          margin: 0 2px;

          &:hover {
            color: #337ecc;
          }
        }
      }
    }

    // 注册按钮
    .login-button-item {
      margin-bottom: 12px;

      .login-button {
        width: 100%;
        height: 44px;
        font-size: 14px;
        font-weight: 600;
        border-radius: 8px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
        }

        &:active {
          transform: translateY(0);
        }

        .button-text {
          letter-spacing: 1px;
        }

        &.is-loading {
          background: linear-gradient(135deg, #a8b3f0 0%, #b19bc8 100%);
        }
      }
    }

    // 登录链接
    .register-link {
      text-align: center;

      .register-text {
        font-size: 12px;
        color: #909399;
        margin-right: 8px;
      }

      .register-btn {
        font-size: 12px;
        font-weight: 600;
        padding: 0;

        &:hover {
          color: #337ecc;
        }
      }
    }
  }
}

// 密码切换按钮
.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f5f7fa;
  }

  .toggle-icon {
    font-size: 14px;
    color: #909399;
    transition: color 0.3s ease;
  }

  &:hover .toggle-icon {
    color: #409eff;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-title {
    .title-content {
      .logo {
        width: 32px;
        height: 32px;
        margin-right: 8px;
      }

      .title-text {
        font-size: 22px;
      }
    }

    .title-subtitle {
      font-size: 12px;
    }
  }

  .login-form-container {
    .login-form {
      .login-button-item .login-button {
        height: 40px;
        font-size: 13px;
      }

      .gender-group {
        gap: 12px;
      }
    }
  }
}

// 动画效果
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-form-container {
  animation: fadeInUp 0.6s ease-out;
}

.form-item {
  animation: fadeInUp 0.6s ease-out;
  animation-fill-mode: both;

  @for $i from 1 through 8 {
    &:nth-child(#{$i}) {
      animation-delay: #{$i * 0.1}s;
    }
  }
}
</style>
